import React from 'react'
import PropTypes from 'prop-types'
import { Image } from 'react-native'
import FastImage from 'react-native-fast-image'
import { isArrayFn, isObjectFn, isString } from '../../utils/JSTypeUtil'
import { ImageHost } from 'src/config/index'
import { IS_ANDROID } from '../../utils/ScreenUtil'

export default function CustomImage (props) {
  let { refImg, style, source, onLoad, onError, ...rest } = props
  let imageStyles = { resizeMode: 'contain' }
  if (isArrayFn(style)) {
    imageStyles = style.reduce((allStyle, currentValue) => ({
      ...allStyle, ...currentValue
    }), imageStyles)
  } else if (isObjectFn(style)) {
    imageStyles = { ...imageStyles, ...style }
  }
  const { width, height, borderRadius } = imageStyles
  if (borderRadius && IS_ANDROID && width === height && borderRadius * 2 >= width) {
    imageStyles.borderRadius = borderRadius * 2
  }
  const { uri } = source || {}
  if (uri && isString(uri) && !uri.startsWith('file')) {
    const resizeMode = imageStyles.resizeMode
    delete imageStyles.resizeMode
    if (!uri.startsWith('http')) {
      source = { uri: ImageHost + uri }
    }
    return (
      <FastImage
        ref={refImg} resizeMode={resizeMode} style={imageStyles} source={source} onLoad={onLoad}
        onError={onError} {...rest} />
    )
  } else {
    return (
      <Image ref={refImg} style={imageStyles} source={source} onLoad={_onLoad} onError={onError} {...rest}/>
    )
  }

  function _onLoad () {
    const { uri } = source || {}
    if (!uri) {
      onError && onError()
    }
  }
}
CustomImage.propTypes = {
  style: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
  source: PropTypes.oneOfType([PropTypes.object, PropTypes.number]),
  refImg: PropTypes.func
}
